package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 *
 * @Author mr.Du
 * @Date 2025/6/20 2025/6/20
 */
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(MyGlobalFilter.class);

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;

    /**
     * 过滤逻辑：校验用户请求中是否携带合法令牌
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("全局过滤器开始过滤");
        //拿到请求和响应实例
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //得到请求相对路径
        String path = request.getURI().getPath();
        //判断是否是白名单路径
        long count = authProperties.getExcludePaths().stream()
                .filter(excludepaths -> antPathMatcher.match(excludepaths, path))
                .count();
        //是,则放行
        if (count > 0) {
            return chain.filter(exchange);
        }
        //不是,拦截获取请求头中的令牌
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        //判断令牌是否为空
        if (StrUtil.isBlank(token)) {
            //令牌为空直接返回401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        try {
            //解析令牌
            Long userId = jwtTool.parseToken(token);
            //解析失败返回401
            if (userId == null) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //解析令牌成功，设置用户信息到请求头
            request.mutate().header("user-info", userId.toString());
            //解析成功放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            // 解析出现异常响应401，直接结束
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
